package com.demo.common.interceptor;

import com.demo.common.constant.ConstantError;
import com.demo.common.dto.ReturnDto;
import com.demo.common.exception.BusinessException;
import com.demo.common.exception.NameRepeatException;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.log.Log;

public class ExceptionInterceptor implements Interceptor {

	private static final Log log = Log.getLog(ExceptionInterceptor.class);
	
	@Override
	public void intercept(Invocation inv) {
		Controller contro = inv.getController();
		try {
			inv.invoke();
		} catch (Exception e) {
			
			if(e instanceof NameRepeatException) {
				toView(contro, ConstantError.NAME_REPEAT, e.getMessage());
			} else if (e instanceof BusinessException) {
				toView(contro, ConstantError.BUSINESS, e.getMessage());
			} else {
				log.error(e.getMessage());
				toView(contro, ConstantError.OHTER, "系统发生异常，请联系管理员!");
			}
		}
	}
	
	private void toView(Controller contro, String errCode, String msg) {
		
		ReturnDto dto = new ReturnDto();
		dto.setSuccess(false);
		dto.setMsg(msg);
		dto.setErrCode(errCode);
		
		String isAjax = contro.getRequest().getHeader("X-Requested-With");
		if(isAjax != null && isAjax.equalsIgnoreCase("XMLHttpRequest")) {
			contro.renderJson(dto);
		} else {
			
		}
	}

}
